<template>
  <div class="timing-scheme-container">
    <!-- 左侧树形结构区域 -->
    <div class="left-tree-panel">
      <div class="tree-header">
        <h4>
          <i class="el-icon-office-building"></i>
          楼栋用房分类
        </h4>
      </div>
      <div class="tree-search">
        <el-input 
          v-model="treeSearchText" 
          placeholder="请输入楼栋内容" 
          size="small" 
          clearable>
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>
      </div>
      <div class="tree-container">
        <el-tree
          :data="treeData"
          :props="treeProps"
          :filter-node-method="filterNode"
          ref="tree"
          node-key="id"
          :expand-on-click-node="false"
          :default-expand-all="true"
          :highlight-current="true"
          @node-click="handleNodeClick"
          class="custom-tree">
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span class="tree-node-label">
              <i :class="getNodeIcon(data)" class="tree-node-icon"></i>
              {{ node.label }}
            </span>
          </span>
        </el-tree>
      </div>
    </div>

    <!-- 右侧内容区域 -->
    <div class="right-content-panel">
      <div class="timing-scheme">
        <!-- Tab切换 -->
        <div class="tab-container">
          <el-tabs v-model="activeTab" @tab-click="handleTabClick" class="custom-tabs">
            <el-tab-pane label="电表定时开控" name="electric-timing">
              <template slot="label">
                <span class="tab-label">
                  <i class="el-icon-lightning"></i>
                  电表定时开控
                </span>
              </template>
            </el-tab-pane>
            <el-tab-pane label="水表定时开控" name="water-timing">
              <template slot="label">
                <span class="tab-label">
                  <i class="el-icon-water-cup"></i>
                  水表定时开控
                </span>
              </template>
            </el-tab-pane>
          </el-tabs>
        </div>
        <!-- 搜索筛选区 -->
        <div class="filter-container">
          <el-form :inline="true" :model="filterForm" class="filter-form">
            <el-form-item label="执行时间:">
              <el-input 
                v-model="filterForm.executionTime" 
                placeholder="请输入"
                clearable
                class="filter-input"
              ></el-input>
            </el-form-item>
            <el-form-item label="执行周期:">
              <el-select 
                v-model="filterForm.executionCycle" 
                placeholder="全部"
                clearable
                class="filter-select"
              >
                <el-option label="全部" value=""></el-option>
                <el-option label="每日" value="daily"></el-option>
                <el-option label="每周" value="weekly"></el-option>
                <el-option label="每月" value="monthly"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="命令:">
              <el-select 
                v-model="filterForm.command" 
                placeholder="全部"
                clearable
                class="filter-select"
              >
                <el-option label="全部" value=""></el-option>
                <el-option label="合闸" value="close"></el-option>
                <el-option label="拉闸" value="open"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="searchData">查询</el-button>
              <el-button icon="el-icon-refresh" @click="resetFilter">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        <!-- 操作按钮区 -->
        <div class="action-container">
          <div class="action-buttons">
            <el-button type="primary" icon="el-icon-plus" @click="addTimingTask">添加定时任务</el-button>
          </div>
        </div>
        <!-- 数据表格 -->
        <div class="table-container">
          <div class="table-header">
            <div class="table-title">
              <i class="el-icon-tickets"></i>
              定时方案列表
            </div>
            <div class="table-info">
              共 {{ tableData.length }} 条数据
            </div>
          </div>
          <el-table 
            :data="tableData" 
            border 
            stripe
            style="width: 100%"
            :header-cell-style="headerCellStyle"
            class="custom-table"
            v-loading="loading"
            element-loading-text="加载中..."
          >
            <el-table-column prop="id" label="序号" width="80" align="center"></el-table-column>
            <el-table-column prop="executionCycle" label="执行周期" width="100" align="center">
              <template slot-scope="scope">
                <el-tag 
                  size="small" 
                  :type="getCycleTypeColor(scope.row.executionCycle)"
                >
                  {{ scope.row.executionCycle }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="executionTime" label="执行时间" width="160" align="center"></el-table-column>
            <el-table-column prop="command" label="命令" width="100" align="center">
              <template slot-scope="scope">
                <el-tag 
                  size="small" 
                  :type="scope.row.command === '合闸' ? 'success' : 'danger'"
                >
                  {{ scope.row.command }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="targetType" label="目标类型" width="120" align="center"></el-table-column>
            <el-table-column prop="nextExecutionTime" label="下次执行时间" width="160" align="center"></el-table-column>
            <el-table-column label="操作" width="240" fixed="right" align="center">
              <template slot-scope="scope">
                <div class="action-buttons">
                  <el-button 
                    type="primary" 
                    size="mini" 
                    icon="el-icon-view"
                    @click="viewTask(scope.row)"
                  >
                    查看
                  </el-button>
                  <el-button 
                    type="warning" 
                    size="mini" 
                    icon="el-icon-edit"
                    @click="editTask(scope.row)"
                  >
                    禁用
                  </el-button>
                  <el-button 
                    type="danger" 
                    size="mini" 
                    icon="el-icon-delete"
                    @click="deleteTask(scope.row)"
                  >
                    删除
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="pagination.currentPage"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="pagination.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="pagination.total"
              class="custom-pagination"
            >
            </el-pagination>
          </div>
        </div>
        <!-- 添加定时任务弹窗 -->
        <el-dialog
          title="添加定时任务"
          :visible.sync="showTaskDialog"
          width="600px"
          class="custom-dialog"
          :close-on-click-modal="false"
        >
          <div class="task-dialog-content">
            <el-form :model="taskForm" :rules="taskRules" ref="taskForm" label-width="120px" class="task-form">
              <el-form-item label="任务名称:" prop="taskName">
                <el-input v-model="taskForm.taskName" placeholder="请输入任务名称"></el-input>
              </el-form-item>
              <el-form-item label="操作类型:" prop="operationType">
                <el-select v-model="taskForm.operationType" placeholder="请选择">
                  <el-option label="合闸" value="close"></el-option>
                  <el-option label="拉闸" value="open"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="执行周期:" prop="executionCycle">
                <el-select v-model="taskForm.executionCycle" placeholder="请选择">
                  <el-option label="每日" value="daily"></el-option>
                  <el-option label="每周" value="weekly"></el-option>
                  <el-option label="每月" value="monthly"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="周末是否执行:" prop="weekendExecution">
                <el-switch 
                  v-model="taskForm.weekendExecution"
                  active-text="是"
                  inactive-text="否"
                ></el-switch>
              </el-form-item>
              <el-form-item label="是否禁用:" prop="disabled">
                <el-switch 
                  v-model="taskForm.disabled"
                  active-text="是"
                  inactive-text="否"
                ></el-switch>
              </el-form-item>
              <el-form-item label="选择房间:">
                <div class="room-selection">
                  <el-button 
                    type="primary" 
                    size="small" 
                    @click="selectRooms"
                    icon="el-icon-plus"
                  >
                    请选择
                  </el-button>
                  <div class="selected-rooms" v-if="taskForm.selectedRooms.length > 0">
                    <el-tag 
                      v-for="room in taskForm.selectedRooms" 
                      :key="room"
                      closable
                      @close="removeRoom(room)"
                      style="margin: 4px;"
                    >
                      {{ room }}
                    </el-tag>
                  </div>
                </div>
              </el-form-item>
            </el-form>
          </div>
          <div slot="footer" class="dialog-footer">
            <el-button @click="showTaskDialog = false">取消</el-button>
            <el-button @click="resetTaskForm">重置</el-button>
            <el-button 
              type="primary" 
              @click="saveTask"
              :loading="saving"
            >
              {{ saving ? '保存中...' : '保存' }}
            </el-button>
          </div>
        </el-dialog>
        <!-- 房间选择弹窗 -->
        <el-dialog
          title="选择房间"
          :visible.sync="showRoomDialog"
          width="500px"
          class="custom-dialog"
        >
          <div class="room-dialog-content">
            <el-tree
              :data="roomTreeData"
              :props="roomTreeProps"
              show-checkbox
              node-key="id"
              ref="roomTree"
              :default-checked-keys="defaultCheckedRooms"
            >
            </el-tree>
          </div>
          <div slot="footer" class="dialog-footer">
            <el-button @click="showRoomDialog = false">取消</el-button>
            <el-button type="primary" @click="confirmRoomSelection">确定</el-button>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>
<script>
import timingSchemeMock from '@/api/mock/timingScheme'
export default {
  name: 'TimingScheme',
  data() {
    return {
      // 树形结构相关
      treeSearchText: '',
      treeData: [],
      selectedNode: null,
      treeProps: {
        children: 'children',
        label: 'label'
      },
      activeTab: 'electric-timing',
      loading: false,
      saving: false,
      tableData: [],
      filterForm: {
        executionTime: '',
        executionCycle: '',
        command: ''
      },
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      showTaskDialog: false,
      showRoomDialog: false,
      taskForm: {
        taskName: '',
        operationType: '',
        executionCycle: '',
        weekendExecution: true,
        disabled: false,
        selectedRooms: []
      },
      taskRules: {
        taskName: [
          { required: true, message: '请输入任务名称', trigger: 'blur' }
        ],
        operationType: [
          { required: true, message: '请选择操作类型', trigger: 'change' }
        ],
        executionCycle: [
          { required: true, message: '请选择执行周期', trigger: 'change' }
        ]
      },
      roomTreeData: [
        {
          id: 'building1',
          label: '微电网研究院_商业',
          children: [
            {
              id: 'floor1',
              label: '一层',
              children: [
                { id: '101', label: '101' },
                { id: '102', label: '102' },
                { id: '103', label: '103' },
                { id: '104', label: '104' }
              ]
            },
            {
              id: 'floor2',
              label: '二层',
              children: [
                { id: '201', label: '201' },
                { id: '202', label: '202' },
                { id: '203', label: '203' }
              ]
            }
          ]
        }
      ],
      roomTreeProps: {
        children: 'children',
        label: 'label'
      },
      defaultCheckedRooms: [],
      headerCellStyle: {
        backgroundColor: '#f8f9fa',
        color: '#495057',
        fontWeight: 'bold',
        textAlign: 'center'
      }
    }
  },
  watch: {
    treeSearchText(val) {
      this.$refs.tree.filter(val)
    }
  },
  mounted() {
    this.loadTreeData()
    this.loadData()
  },
  methods: {
    // 加载树形结构数据 - 使用mock数据
    loadTreeData() {
      // 直接使用mock数据，避免API请求
      this.treeData = [
        {
          id: 1,
          label: '楼栋用房分类',
          children: [
            {
              id: 2,
              label: '宿舍',
              children: [
                {
                  id: 3,
                  label: 'A栋',
                  children: [
                    { id: 4, label: '101', roomId: 101, buildingId: 3 },
                    { id: 5, label: '102', roomId: 102, buildingId: 3 },
                    { id: 6, label: '103', roomId: 103, buildingId: 3 },
                    { id: 7, label: '104', roomId: 104, buildingId: 3 }
                  ]
                }
              ]
            },
            {
              id: 8,
              label: '二层',
              children: [
                {
                  id: 9,
                  label: 'B栋',
                  children: [
                    { id: 10, label: '201', roomId: 201, buildingId: 9 },
                    { id: 11, label: '202', roomId: 202, buildingId: 9 },
                    { id: 12, label: '203', roomId: 203, buildingId: 9 }
                  ]
                }
              ]
            }
          ]
        }
      ]
    },
    
    // 树形结构过滤方法
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    
    // 树形节点点击事件
    handleNodeClick(data) {
      console.log('选中节点:', data)
      this.selectedNode = data
      // 根据选中的节点过滤表格数据
      this.loadData()
    },
    
    // 获取节点图标
    getNodeIcon(data) {
      if (data.roomId) {
        return 'el-icon-house'
      } else if (data.buildingId) {
        return 'el-icon-office-building'
      } else if (data.children && data.children.length > 0) {
        return 'el-icon-folder-opened'
      } else {
        return 'el-icon-folder'
      }
    },
    getCycleTypeColor(cycle) {
      switch (cycle) {
        case '每日':
          return 'success'
        case '每周':
          return 'warning'
        case '每月':
          return 'info'
        default:
          return ''
      }
    },
    loadData() {
      this.loading = true
      setTimeout(() => {
        let response = timingSchemeMock
        let filteredData = response.msg.list

        // 根据选中的树节点过滤数据
        if (this.selectedNode && this.selectedNode.roomId) {
          filteredData = filteredData.filter(item => 
            item.targetType.includes(this.selectedNode.label)
          )
        }

        // Apply filterForm filters
        if (this.filterForm.executionTime) {
          filteredData = filteredData.filter(item => item.executionTime.includes(this.filterForm.executionTime))
        }
        if (this.filterForm.executionCycle) {
          filteredData = filteredData.filter(item => item.executionCycle === this.filterForm.executionCycle)
        }
        if (this.filterForm.command) {
          filteredData = filteredData.filter(item => item.command === this.filterForm.command)
        }

        this.pagination.total = filteredData.length
        const start = (this.pagination.currentPage - 1) * this.pagination.pageSize
        const end = start + this.pagination.pageSize
        this.tableData = filteredData.slice(start, end)
        this.loading = false
      }, 500)
    },
    searchData() {
      this.pagination.currentPage = 1
      this.loadData()
    },
    resetFilter() {
      this.filterForm = {
        executionTime: '',
        executionCycle: '',
        command: ''
      }
      this.pagination.currentPage = 1
      this.loadData()
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.loadData()
    },
    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.loadData()
    },
    handleTabClick(tab) {
      console.log('切换到:', tab.name)
      // 根据tab切换加载不同的数据或调整过滤逻辑
      this.loadData()
    },
    addTimingTask() {
      this.showTaskDialog = true
      this.resetTaskForm()
    },
    viewTask(row) {
      this.$message.info(`查看任务: ${row.id}`)
      // 实际查看逻辑
    },
    editTask(row) {
      this.$message.info(`禁用任务: ${row.id}`)
      // 实际禁用逻辑
    },
    deleteTask(row) {
      this.$confirm(`确认删除任务 ${row.id} 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message.success('删除成功!')
        this.loadData() // 刷新数据
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    selectRooms() {
      this.defaultCheckedRooms = this.taskForm.selectedRooms.map(room => room)
      this.showRoomDialog = true
      this.$nextTick(() => {
        if (this.$refs.roomTree) {
          this.$refs.roomTree.setCheckedKeys(this.defaultCheckedRooms)
        }
      })
    },
    confirmRoomSelection() {
      this.taskForm.selectedRooms = this.$refs.roomTree.getCheckedKeys().filter(key => typeof key === 'string' && !key.includes('building') && !key.includes('floor'))
      this.showRoomDialog = false
    },
    removeRoom(roomToRemove) {
      this.taskForm.selectedRooms = this.taskForm.selectedRooms.filter(room => room !== roomToRemove)
    },
    saveTask() {
      this.$refs.taskForm.validate(valid => {
        if (valid) {
          this.saving = true
          setTimeout(() => {
            this.$message.success('任务保存成功！')
            this.saving = false
            this.showTaskDialog = false
            this.loadData() // 刷新数据
          }, 1500)
        } else {
          this.$message.error('请检查表单项！')
          return false
        }
      })
    },
    resetTaskForm() {
      this.taskForm = {
        taskName: '',
        operationType: '',
        executionCycle: '',
        weekendExecution: true,
        disabled: false,
        selectedRooms: []
      }
      this.$nextTick(() => {
        this.$refs.taskForm.clearValidate()
      })
    }
  }
}
</script>
<style scoped>
/* 主容器样式 */
.timing-scheme-container {
  display: flex;
  height: calc(100vh - 120px); /* 减去头部和底部的高度 */
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

/* 左侧树形结构面板 */
.left-tree-panel {
  width: 300px;
  background: white;
  border-radius: 12px 0 0 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  margin: 24px 0 24px 24px;
}

.tree-header {
  padding: 20px 20px 0;
  border-bottom: 1px solid #e9ecef;
}

.tree-header h4 {
  margin: 0 0 20px 0;
  color: #2c3e50;
  font-size: 16px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
}

.tree-header h4 i {
  color: #3498db;
  font-size: 18px;
}

.tree-search {
  padding: 20px;
  border-bottom: 1px solid #e9ecef;
}

.tree-container {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.custom-tree {
  background: transparent;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  font-size: 14px;
  padding-right: 8px;
}

.tree-node-label {
  display: flex;
  align-items: center;
  gap: 8px;
}

.tree-node-icon {
  color: #3498db;
  font-size: 16px;
}

/* 右侧内容面板 */
.right-content-panel {
  flex: 1;
  background: white;
  border-radius: 0 12px 12px 0;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  margin: 24px 24px 24px 0;
  padding: 24px;
}

/* Tab切换 */
.tab-container {
  margin-bottom: 20px;
}

.custom-tabs .el-tabs__header {
  margin-bottom: 0;
}

.custom-tabs .el-tabs__nav-wrap::after {
  height: 0;
}

.tab-label {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
}

/* 搜索筛选区 */
.filter-container {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.filter-form .el-form-item {
  margin-bottom: 10px;
  margin-right: 20px;
}

.filter-input,
.filter-select {
  width: 180px;
}

/* 操作按钮区 */
.action-container {
  margin-bottom: 20px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

/* 数据表格 */
.table-container {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.table-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  display: flex;
  align-items: center;
  gap: 8px;
}

.table-title i {
  color: #409eff;
}

.table-info {
  font-size: 14px;
  color: #606266;
}

.custom-table {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

/* 操作按钮组 */
.custom-table .action-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 5px; /* 按钮之间的间距 */
  justify-content: center; /* 居中显示 */
}

/* 分页 */
.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 弹窗样式 */
.custom-dialog .el-dialog__header {
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  padding: 20px;
}

.custom-dialog .el-dialog__title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.task-dialog-content,
.room-dialog-content {
  padding: 20px;
}

.task-form .el-form-item {
  margin-bottom: 20px;
}

.room-selection {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 10px;
}

.selected-rooms {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.dialog-footer {
  padding: 20px;
  text-align: right;
  border-top: 1px solid #ebeef5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .timing-scheme-container {
    flex-direction: column;
    height: auto;
  }

  .left-tree-panel {
    width: auto;
    margin: 10px;
    border-radius: 12px;
  }

  .right-content-panel {
    margin: 10px;
    border-radius: 12px;
    padding: 15px;
  }

  .filter-form {
    flex-direction: column;
    align-items: flex-start;
  }

  .filter-form .el-form-item {
    margin-right: 0;
    width: 100%;
  }

  .filter-input,
  .filter-select {
    width: 100%;
  }

  .action-buttons {
    flex-direction: column;
  }

  .action-buttons .el-button {
    width: 100%;
  }
}
</style>


